import { Observable, throwError } from 'rxjs';
import { catchError, map, timeout } from 'rxjs/operators';
import { CallHandler, ExecutionContext, HttpException, Injectable, NestInterceptor } from '@nestjs/common';

@Injectable()
export class TransformInterceptor implements NestInterceptor {
    intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> | Promise<Observable<any>> {
        return next
            .handle()
            .pipe(timeout(5000), map(TransformInterceptor.success), catchError(TransformInterceptor.error));
    }

    static success(data: any) {
        return {
            statusCode: 200,
            data,
        };
    }

    static error(err: any) {
        console.error('🚀 ~ file: transform.interceptor.ts:23 ~ TransformInterceptor ~ error ~ err:', err);
        const errorMessage = [
            {
                condition: () => err instanceof HttpException,
                value: () => ({
                    success: false,
                    statusCode: err.getStatus(),
                    message: err.getResponse(),
                }),
            },
            {
                condition: () => err.code === 11000,
                value: () => ({
                    success: false,
                    statusCode: 400,
                    message: err.message,
                }),
            },
            {
                condition: () => !!err._message,
                value: () => ({
                    success: false,
                    statusCode: 400,
                    message: err._message,
                }),
            },
            {
                condition: () => true,
                value: () => ({
                    success: false,
                    statusCode: 500,
                    message: 'Internal server error',
                }),
            },
        ]
            .find((item) => !!item.condition())
            .value();

        return throwError(() => errorMessage);
    }
}
